<?php
/**
 * Created by PhpStorm.
 * User: stc17
 * Date: 2020/3/4
 * Time: 8:35
 */

namespace SwoStar\Server\WebSocket;


use SwoStar\Console\Input;

use SwoStar\Server\Http\HttpServer;
use Swoole\WebSocket\Server as SwooleServer;
use Swoole\Http\Request;
use Swoole\Http\Response;

class WebSocketServer extends HttpServer
{

    /**
     * 创建服务
     */
    public  function createServer()
    {
        $this->swooleServer=new SwooleServer($this->host,$this->port);
        Input::info('websocket server 访问 ws://192.168.157.240:'.$this->port);
    }
    /**
     * 初始化监听的事件
     */
    protected  function initEvent()
    {
        $event=[
            'request'   =>'onRequest',
            'open'      =>'onOpen',
            'message'   =>'onMessage',
            'close'     =>'onClose',
          ];
        //判断是否自定义握手过程
        ($this->app->make('config')->get('server.ws.is_handshake'))?$event['handshake']='onHandshake':'';

        $this->setEvent('sub',$event);
    }

    //监听客户端对in-server的请求
    public function onHandShake(Request $request, Response $response){
        $this->app->make('event')->trigger('ws.hand', [$this, $request, $response]);

        //因为设置了onHandShake回调函数，就不会触发onOpen
        $this->onOpen($this->swooleServer,$request);
    }

    public  function onOpen(SwooleServer $server, $request)
    {
        //记录fd 和访问地址
        Connections::init($request->fd,$request);

        $return=app('route')->setFlag('WebSocket')->setMethod('open')
            ->match($request->server['path_info'],[$server,$request]);
    }
    public  function onMessage(SwooleServer $server, $frame)
    {
       $path=((Connections::get($frame->fd))['path']);

       //消息回复事件
        $this->app->make('event')->trigger('ws.message.front', [$this, $server, $frame]);


        //消息业务流程
        $return=app('route')->setFlag('WebSocket')->setMethod('message')
            ->match($path,[$server,$frame]);

    }
    public  function onClose($ser, $fd){
        $path=((Connections::get($fd))['path']);
        $return=app('route')->setFlag('WebSocket')->setMethod('close')
            ->match($path,[$ser,$fd]);
        $this->app->make('event')->trigger('ws.close', [$this, $ser, $fd]);

        Connections::del($fd);
    }


    //对当前服务群发
    public function sendAll($msg)
    {
        dd($this->swooleServer->connections->fd ,'对当前服务群发');
        foreach ($this->swooleServer->connections as $key=>$fd){

            if($this->swooleServer->exists($fd)){
                $this->swooleServer->push($fd,$msg);
            }
        }
    }



}